package org.finesys.common.mp.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.finesys.common.constants.BaseConstant;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * 字段数据填充
 */
public class DefaultFieldHandler implements MetaObjectHandler {

    private final static String CREATE_TIME = "createTime";

    private final static String CREATE_BY = "createBy";

    private final static String UPDATE_TIME = "updateTime";

    private final static String UPDATE_BY = "updateBy";

    private final static String DELETE_FIELD = "delFlag";

    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        // 创建时间
        fillValIfNullByName(CREATE_TIME, now, metaObject, false);
        // 更新时间
        fillValIfNullByName(UPDATE_TIME, now, metaObject, false);
        // 创建者
        fillValIfNullByName(CREATE_BY, getUserName(), metaObject, false);
        // 更新者
        fillValIfNullByName(UPDATE_BY, getUserName(), metaObject, false);
        // 删除标记自动填充
        fillValIfNullByName(DELETE_FIELD, BaseConstant.NORMAL, metaObject, true);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        fillValIfNullByName(UPDATE_TIME, now, metaObject, true);
        fillValIfNullByName(UPDATE_BY, getUserName(), metaObject, true);
    }

    /**
     * 对字段是否填充
     */
    private void fillValIfNullByName(String fieldName, Object fieldVal, MetaObject metaObject, boolean isCovor) {
        // 0. 如果填充值为空
        if (fieldVal == null) {
            return;
        }
        /** 判断是否存在字段 */
        if (!metaObject.hasSetter(fieldName)) {
            return;
        }
        // 如果用户有设置值
        Object userSetVal = metaObject.getValue(fieldName);
        if (!ObjectUtils.isEmpty(userSetVal) && !isCovor) {
            return;
        }
        // 类型相同时设置
        Class<?> getterType = metaObject.getGetterType(fieldName);
        if (ClassUtils.isAssignableValue(getterType, fieldVal)) {
            metaObject.setValue(fieldName, fieldVal);
        }
    }

    private String getUserName() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        // 匿名接口直接返回
        if (authentication instanceof AnonymousAuthenticationToken) {
            return null;
        }
        //返回登录用户信息
        if (Optional.ofNullable(authentication).isPresent()) {
            return authentication.getName();
        }
        return null;
    }

}
